package org.server.action.actionController.login;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.iohao.game.action.skeleton.annotation.ActionController;
import com.iohao.game.action.skeleton.annotation.ActionMethod;
import com.iohao.game.action.skeleton.protocol.wrapper.LongValue;
import com.iohao.game.action.skeleton.protocol.wrapper.StringValue;
import com.iohao.game.bolt.broker.client.external.session.UserSession;
import com.iohao.game.bolt.broker.client.external.session.UserSessions;
import lombok.extern.slf4j.Slf4j;
import org.server.action.ActionCmd;
import org.server.common.RedisUtil;
import org.server.domain.Result.Msg;
import org.server.service.LoginService;
import org.server.service.PokerService;
import org.server.service.RoomService;
import org.server.task.RoomDealTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@ActionController(ActionCmd.ADMIN)
public class AdminAction {

    @Autowired
    private PokerService pokerService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private LoginService loginService;

    @ActionMethod(ActionCmd.ADMIN_KICK)
    public void kickPlayer(LongValue userId) {
        try {
            UserSessions me = UserSessions.me();
            UserSession userSession = me.getUserSession(userId.value);

            me.removeUserSession(userSession);
        } catch (RuntimeException e) {
            log.info(e.getMessage());
        }
    }

    @ActionMethod(ActionCmd.ADMIN_ONLINE)
    public StringValue onlinePlayer(StringValue stringValue) {
        try {
            UserSessions me = UserSessions.me();
            long countOnline = me.countOnline();
            StringValue msg = new StringValue();
            msg.value = String.valueOf(countOnline);
            return msg;
        } catch (RuntimeException e) {
            log.info(e.getMessage());
        }
        return stringValue;
    }

    @ActionMethod(ActionCmd.ADMIN_DEAL)
    public Msg dealByAdmin(StringValue stringValue) {
        String roomName = stringValue.value;

        List<Long> playerList = JSONArray.parseArray((String) redisUtil.getValueInHash(roomName, RoomService.PLAY_LIST), Long.class);

        log.error(playerList.toString());

        redisUtil.setHash(roomName, RoomService.STATUS, RoomService.ROOM_PLAYING);
        redisUtil.setHash(roomName, RoomService.CURRENT, JSON.toJSONString(playerList.get(0)));

        new RoomDealTask()
                .setPokerService(pokerService)
                .setPlayerList(playerList)
                .setRoomName(roomName)
                .setRedisUtil(redisUtil)
                .setLoginService(loginService)
                .setDelayExecutionTime(RoomService.DELAY_TIME)
                .task();
        return new Msg("发牌成功");
    }
}
